#!/usr/bin/env bash
BASE_DIR="$(dirname $0)"
PYSPIDER_COFNIG_FILE="$BASE_DIR/pyspider_config.json"
HKEX_SPIDER_CONFIG_FILE="$BASE_DIR/plugin/configs.py"
HKEX_PUSH_JUHCAO_CONFIG_FILE="$BASE_DIR/hkex_push_juhcao/config.py"
EXPORT_ENV_FILE="$BASE_DIR/export/env.py"
SUPERVIOR_CONFIG_FILE="$BASE_DIR/supervisorctl_conf/hkex_spider.ini"
SUPERVIOR_CONFIG_COPY_FILE="$BASE_DIR/hkex_spider.ini"

build_env(){
echo "$(date "+%Y-%m-%d %H:%M:%S") start build $1 env"
case "$1" in
  prod)
        sed -i "s/pysp_sys_rw_te/pysp_sys_rw_pe/g" $PYSPIDER_COFNIG_FILE
        sed -i "s/rldJ4m9kl2EX/OmAvWHDd1YAc/g" $PYSPIDER_COFNIG_FILE
        sed -i "s/pyspider_taskdb_pre/pyspider_taskdb/g" $PYSPIDER_COFNIG_FILE
        sed -i "s/pyspider_projectdb_pre/pyspider_projectdb/g" $PYSPIDER_COFNIG_FILE
        sed -i "s/pyspider_resultdb_pre/pyspider_resultdb/g" $PYSPIDER_COFNIG_FILE
        sed -i "s/172.31.223.204/172.31.223.207/g" $PYSPIDER_COFNIG_FILE
        sed -i "s/i3UmqJSmwodB/R6Wmkm9jhhpU/g" $PYSPIDER_COFNIG_FILE
        sed -i "s/env = 'test'/env = 'prod'/g" $HKEX_SPIDER_CONFIG_FILE
        sed -i "s/env = 'test'/env = 'prod'/g" $HKEX_PUSH_JUHCAO_CONFIG_FILE
        sed -i "s/ENV = 'online_dev'/ENV = 'online'/g" $EXPORT_ENV_FILE
        sed -i "s/online-pre-hkex_spider/online-prod-hkex_spider/g" $SUPERVIOR_CONFIG_FILE
    ;;
  test)
        sed -i "s/pysp_sys_rw_pe/pysp_sys_rw_te/g" $PYSPIDER_COFNIG_FILE
        sed -i "s/OmAvWHDd1YAc/rldJ4m9kl2EX/g" $PYSPIDER_COFNIG_FILE
        sed -i "s/pyspider_taskdb_pre/pyspider_taskdb/g" $PYSPIDER_COFNIG_FILE
        sed -i "s/pyspider_projectdb_pre/pyspider_projectdb/g" $PYSPIDER_COFNIG_FILE
        sed -i "s/pyspider_resultdb_pre/pyspider_resultdb/g" $PYSPIDER_COFNIG_FILE
        sed -i "s/pyspider_taskdb/pyspider_taskdb_pre/g" $PYSPIDER_COFNIG_FILE
        sed -i "s/pyspider_projectdb/pyspider_projectdb_pre/g" $PYSPIDER_COFNIG_FILE
        sed -i "s/pyspider_resultdb/pyspider_resultdb_pre/g" $PYSPIDER_COFNIG_FILE
        sed -i "s/172.31.223.207/172.31.223.204/g" $PYSPIDER_COFNIG_FILE
        sed -i "s/R6Wmkm9jhhpU/i3UmqJSmwodB/g" $PYSPIDER_COFNIG_FILE
        sed -i "s/env = 'prod'/env = 'test'/g" $HKEX_SPIDER_CONFIG_FILE
        sed -i "s/env = 'prod'/env = 'test'/g" $HKEX_PUSH_JUHCAO_CONFIG_FILE
        sed -i "s/ENV = 'online'/ENV = 'online_dev'/g" $EXPORT_ENV_FILE
        sed -i "s/online-prod-hkex_spider/online-pre-hkex_spider/g" $SUPERVIOR_CONFIG_FILE

    ;;
  *)
esac
server_name=`hostname`
cp $SUPERVIOR_CONFIG_FILE $SUPERVIOR_CONFIG_COPY_FILE
if test $server_name = "nj-gjs-srv005";then
  sed -n '24,74p' $SUPERVIOR_CONFIG_FILE > $SUPERVIOR_CONFIG_COPY_FILE
fi
cp $SUPERVIOR_CONFIG_COPY_FILE /etc/supervisord.d/
echo "$(date "+%Y-%m-%d %H:%M:%S")  build finished!"
}
case "$1" in
  test)
    build_env $1
    ;;
  prod)
    build_env $1
    ;;
  *)
  echo $"Usage: buikd_env.sh {test|prod}"
  exit 110
esac
